'''
Author: zhanwei xu
Date: 2023-07-03 17:57:54
LastEditors: zhanwei xu
LastEditTime: 2023-07-03 17:58:43
Description: 

Copyright (c) 2023 by zhanwei xu, Tsinghua University, All Rights Reserved. 
'''
import os
import signal
import subprocess
import time

def find_process_id(command):
    # 查找进程ID
    ps = subprocess.Popen("ps aux | grep -v grep | grep '{}'".format(command), shell=True, stdout=subprocess.PIPE)
    output, _ = ps.communicate()
    pids = []
    print(output.decode())
    for line in output.decode().split('\n'):
        if line:
            pids.append(int(line.split()[1]))

    return pids

def kill_process(pids):
    # 杀死进程
    for pid in pids:
        try:
            os.kill(pid, signal.SIGKILL)
        except:
            pass
        try:
            os.kill(pid+1, signal.SIGKILL)
        except:
            pass
        try:
            os.kill(pid+2, signal.SIGKILL)
        except:
            pass
        try:
            os.kill(pid+3, signal.SIGKILL)
        except:
            pass
        print(pid)

def restart_service(command):
    # 重启服务
    subprocess.Popen(command, shell=True)

if __name__ == '__main__':
    service_command = "uvicorn server:app --host 0.0.0.0 --port 8100 --log-level warning --workers 3"
    
    # 查找并杀死进程
    pids = find_process_id(service_command)
    kill_process(pids)

    # 等待一段时间，确保进程被杀死
    time.sleep(2)

    # 重启服务
    restart_service(service_command)

    while True:
        # 等待一段时间，确保进程被杀死
        time.sleep(24*60*60)

            
        # 查找并杀死进程
        pids = find_process_id(service_command)
        kill_process(pids)

        # 等待一段时间，确保进程被杀死
        time.sleep(2)

        # 重启服务
        restart_service(service_command)
